JavaScript syntax
part 52/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
function Foo() {}
// Use of 'new' sets prototype slots (for example,
// x = new Foo() would set x's prototype to Foo.prototype,
// and Foo.prototype has a constructor slot pointing back to Foo).
const x = new Foo();
// The above is almost equivalent to
const y = {};
y.constructor = Foo;
y.constructor();
// Except
x.constructor == y.constructor; // true
x instanceof Foo; // true
y instanceof Foo; // false
// y's prototype is Object.prototype, not
// Foo.prototype, since it was initialized with
// {} instead of new Foo.
// Even though Foo is set to y's constructor slot,
// this is ignored by instanceof - only y's prototype's
// constructor slot is considered.
Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. (The function object also has a special prototype property, as discussed in the "Inheritance" section below.)
Object deletion is rarely used as the scripting engine will garbage collect objects that are no longer being referenced.
Inheritance
JavaScript supports inheritance hierarchies through prototyping in the manner of Self.
In the following example, the Derived class inherits from the Base class. When d is created as Derived, the reference to the base instance of Base is copied to d.base.
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────